/**
 * 
 */
package edu.arizona.eller.mis.hippo.facade;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import edu.arizona.eller.mis.hippo.facade.helper.SignedRequestsHelper;

/**
 * @author Michael Zawacki
 * 
 */
public class AmazonFacade {

	public Document fullSearch(String queryTerm) throws Throwable {
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("Operation", "ItemSearch");
		myMap.put("Service", "AWSECommerceService");
		myMap.put("SearchIndex", "All");
		myMap.put("ResponseGroup", "Medium");
		myMap.put("Keywords", queryTerm);

		SignedRequestsHelper request = new SignedRequestsHelper();
		String urlRequest = request.sign(myMap);
		String result = connect(urlRequest);
		InputStream is = new ByteArrayInputStream(result.getBytes("UTF-8"));
		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder builder = domFactory.newDocumentBuilder();

		Document doc = builder.parse(is);
		return doc;

	}

	public Document conditionSearch(String queryTerm, String conditionTerm)throws Throwable {
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("Operation", "ItemSearch");
		myMap.put("Service", "AWSECommerceService");
		myMap.put("SearchIndex", "All");
		myMap.put("Condition", conditionTerm);
		myMap.put("ResponseGroup", "Medium");
		myMap.put("Keywords", queryTerm);

		SignedRequestsHelper request = new SignedRequestsHelper();
		String urlRequest = request.sign(myMap);
		String result = connect(urlRequest);
		InputStream is = new ByteArrayInputStream(result.getBytes("UTF-8"));
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = domFactory.newDocumentBuilder();

		Document doc = builder.parse(is);
		return doc;
	}

	private String connect(String urlRequest) throws Throwable {
		URL url;
		StringBuffer result = new StringBuffer();

		try {
			url = new URL(urlRequest);
			InputStreamReader is = new InputStreamReader(url.openStream());
			BufferedReader in = new BufferedReader(is);
			String inputLine;

			while ((inputLine = in.readLine()) != null){
				result.append(inputLine);
			}
			in.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result.toString();
	}
}
